<template>
  <div class="page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="page-title">
        <h2>🧹 卫生评分管理</h2>
        <p class="page-subtitle">管理宿舍卫生评分，包括评分记录、统计分析等</p>
      </div>
      <div class="header-actions">
        <el-button size="large" @click="refreshScores">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="search-section">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索房间号、评分员..."
          size="large"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>
      <div class="filter-section">
        <el-select v-model="scoreFilter" placeholder="全部评分" size="large" clearable style="width: 160px">
          <el-option label="优秀" value="excellent" />
          <el-option label="良好" value="good" />
          <el-option label="不合格" value="poor" />
        </el-select>
        <el-select v-model="floorFilter" placeholder="全部楼层" size="large" clearable style="width: 140px">
          <el-option label="1楼" value="1" />
          <el-option label="2楼" value="2" />
          <el-option label="3楼" value="3" />
          <el-option label="4楼" value="4" />
        </el-select>
        <el-date-picker
          v-model="dateFilter"
          type="date"
          placeholder="选择日期"
          size="large"
          clearable
          style="width: 180px"
        />
      </div>
    </div>

    <!-- 评分列表 -->
    <el-card class="table-card">
      <el-table :data="filteredScores" size="large" stripe style="width: 100%" v-loading="loading">
        <el-table-column label="房间信息" width="150">
          <template #default="{ row }">
            <div class="room-info">
              <div class="room-number">{{ getRoomInfo(row.roomId).roomNumber }}</div>
              <div class="room-floor">{{ getRoomInfo(row.roomId).floor }}楼</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)" size="large">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="学期" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.semester || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="管理员ID" width="150">
          <template #default="{ row }">
            <div class="evaluator-info">
              <div class="evaluator-name">{{ row.adminId || '-' }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="评分时间" width="150">
          <template #default="{ row }">
            <span class="score-date">{{ formatDate(row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="viewScore(row)">
                <el-icon><View /></el-icon>
              </el-button>
              <el-button type="danger" size="small" @click="deleteScore(row)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 查看评分详情模态框 -->
    <el-dialog
      v-model="showViewModal"
      title="👁️ 评分详情"
      width="500px"
      :before-close="closeViewModal"
    >
      <div v-if="selectedScore">
        <el-descriptions :column="1" border size="large">
          <el-descriptions-item label="房间号">
            {{ getRoomInfo(selectedScore.roomId).roomNumber }}
          </el-descriptions-item>
          <el-descriptions-item label="楼层">
            {{ getRoomInfo(selectedScore.roomId).floor }}楼
          </el-descriptions-item>
          <el-descriptions-item label="类型">
            <el-tag :type="getTypeTagType(selectedScore.type)" size="large">
              {{ getTypeText(selectedScore.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学期">
            {{ selectedScore.semester || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="管理员ID">
            {{ selectedScore.adminId || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="评分时间">
            {{ formatDateTime(selectedScore.createTime) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button size="large" @click="closeViewModal">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, Search, View, Delete } from '@element-plus/icons-vue'
import { 
  queryHygieneAPI, 
  deleteHygieneAPI 
} from '@/apis/hygieneAPI'
import { queryRoomAPI } from '@/apis/roomAPI'

// 响应式数据
const loading = ref(false)
const searchQuery = ref('')
const scoreFilter = ref('')
const floorFilter = ref('')
const dateFilter = ref('')
const showViewModal = ref(false)
const selectedScore = ref(null)
const scores = ref([])
const rooms = ref([])

// 根据 roomId 获取房间信息
const getRoomInfo = (roomId) => {
  const room = rooms.value.find(r => String(r.id) === String(roomId))
  if (room) {
    return {
      roomNumber: room.roomNumber || room.number || roomId || '-',
      floor: room.floor || '-'
    }
  }
  return { roomNumber: roomId || '-', floor: '-' }
}

// 计算属性 - 前端筛选
const filteredScores = computed(() => {
  let filtered = scores.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(score => {
      const room = getRoomInfo(score.roomId)
      const roomNumber = (room.roomNumber || '').toString().toLowerCase()
      const adminId = (score.adminId || '').toString().toLowerCase()
      const semester = (score.semester || '').toString().toLowerCase()
      return roomNumber.includes(query) || adminId.includes(query) || semester.includes(query)
    })
  }

  // 评分过滤（根据类型过滤）
  if (scoreFilter.value && filtered.length > 0) {
    filtered = filtered.filter(score => {
      // 根据类型过滤
      switch (scoreFilter.value) {
        case 'excellent': return score.type === 0  // 优秀
        case 'good': return score.type === 1        // 良好
        case 'poor': return score.type === 2        // 不合格
        default: return true
      }
    })
  }

  // 楼层过滤
  if (floorFilter.value) {
    filtered = filtered.filter(score => {
      const room = getRoomInfo(score.roomId)
      return String(room.floor) === String(floorFilter.value)
    })
  }

  // 日期过滤
  if (dateFilter.value) {
    const filterDate = new Date(dateFilter.value).toDateString()
    filtered = filtered.filter(score => {
      const scoreDate = score.createTime
      if (!scoreDate) return false
      return new Date(scoreDate).toDateString() === filterDate
    })
  }

  return filtered
})

// 获取卫生评分数据
const fetchScores = async () => {
  loading.value = true
  try {
    const response = await queryHygieneAPI({})
    
    if (response.code === 0) {
      scores.value = response.data || []
    } else {
      ElMessage.error(response.msg || '获取卫生评分失败')
      scores.value = []
    }
  } catch (error) {
    console.error('获取卫生评分失败:', error)
    ElMessage.error('获取卫生评分失败')
    scores.value = []
  } finally {
    loading.value = false
  }
}

// 方法
const getTypeText = (type) => {
  if (type === 0) return '优秀'
  if (type === 1) return '良好'
  if (type === 2) return '不合格'
  return '-'
}

const getTypeTagType = (type) => {
  if (type === 0) return 'success'  // 优秀 - 绿色
  if (type === 1) return 'primary'  // 良好 - 蓝色
  if (type === 2) return 'danger'   // 不合格 - 红色
  return 'info'
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const formatDateTime = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

const refreshScores = () => {
  fetchScores()
}

const viewScore = (score) => {
  selectedScore.value = score
  showViewModal.value = true
}

const deleteScore = async (score) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除该卫生评分记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    const response = await deleteHygieneAPI(score.id)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      await fetchScores()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除卫生评分失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

const closeViewModal = () => {
  showViewModal.value = false
  selectedScore.value = null
}

onMounted(async () => {
  // 初始化数据
  await Promise.all([
    fetchScores(),
    // 加载所有房间（用于显示房间信息）
    (async () => {
      try {
        const rRes = await queryRoomAPI({ pageNum: 1, pageSize: 999 })
        rooms.value = rRes.data?.records || rRes.data || []
      } catch (error) {
        console.error('获取房间列表失败:', error)
      }
    })()
  ])
})
</script>

<style scoped>
.page {
  width: 100%;
  max-width: 100%;
  padding: 0;
  margin: 0;
}

.page-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-title h2 {
  font-size: 28px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 6px 0;
}

.page-subtitle {
  font-size: 16px;
  color: #6b7280;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.search-box {
  flex: 1;
  max-width: 350px;
}

.filter-section {
  display: flex;
  gap: 16px;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.table-card :deep(.el-card__body) {
  padding: 20px;
}

.table-card :deep(.el-table) {
  width: 100% !important;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 表格内容样式 */
.room-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.room-number {
  font-weight: 500;
  color: #1f2937;
  font-size: 16px;
}

.room-floor {
  font-size: 14px;
  color: #6b7280;
}

.evaluator-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.evaluator-name {
  font-weight: 500;
  color: #1f2937;
  font-size: 16px;
}

.score-date {
  color: #6b7280;
  font-size: 16px;
}

.action-buttons {
  display: flex;
  gap: 2px;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
}

/* 增大表格字体和间距 */
:deep(.el-table) {
  font-size: 16px;
}

:deep(.el-table th) {
  font-size: 16px;
  font-weight: 600;
  padding: 16px 0;
}

:deep(.el-table td) {
  padding: 16px 0;
}

:deep(.el-table .cell) {
  font-size: 16px;
  line-height: 1.6;
}

/* 增大标签字体 */
:deep(.el-tag) {
  font-size: 14px;
  padding: 8px 12px;
}

/* 增大按钮字体 */
:deep(.el-button) {
  font-size: 14px;
  padding: 10px 16px;
}

/* 操作按钮特殊样式 */
:deep(.action-buttons .el-button) {
  padding: 4px 6px;
  font-size: 12px;
  min-width: auto;
  width: 32px;
  height: 32px;
}

:deep(.action-buttons .el-button .el-icon) {
  font-size: 14px;
}
</style>
